import axios from 'axios'
// import router from '@/router'
import store from '@/store'
import helper from './helper'

// 创建axios实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: '/' + process.env.VUE_APP_API_PREFIX,
  // timeout
  timeout: 60 * 1000
})

// // 请求拦截器
request.interceptors.request.use((config) => {
  // heartbeat
  // dink.setStorage('lastRequestTime', dink.now())
  // header
  // config.headers.Encrypt = configLocal.encrypt.enable
  if (store.state.token) {
    Object.assign(config.headers, { 'X-Access-Token': store.state.token })
  }
  return config
}, (error) => {
  return Promise.reject(error)
})
//
// // 响应拦截器
request.interceptors.response.use((response) => {
  return response.data
}, (error) => {
  // helper.msg.error(error.response.data.message || error.message)
  if (error.response.status === 423) {
    helper.msg.error('登录过期')
    store.commit('logout')
    // router.push({ name: 'login' })
  } else {
    helper.msg.error(error.response.data.message || error.message)
  }
  if (error.response.status === 500 && error.response.config.url === '/protal/portalLogin/user') {
    return error.response
  }
  if (error.response.status === 404) {
    helper.msg.error(error.message)
    this.$router.push('/403')
  }
  if (error.response.status === 403) {
    helper.msg.error(error.message)
  }
  // if (error.response.status === 500 && error.response.data.message === 'Token失效，请重新登录') {
  //   helper.msg.error('登录超时')
  //   helper.storage.clear()
  //   router.push({ name: 'login' })
  // } else {
  //   helper.msg.error(error.message)
  // }
  return Promise.reject(error)
})

const http = (url, data, options = {}) => {
  // const result = axios({
  const result = request({
    url: url,
    method: options.method,
    params: options.method === 'get' ? data : {},
    data: data
  })
  return result
}

const dom = (url, data, options = {}) => {
  options.method = 'get'
  return http(url, data, options)
}

const get = (url, data, options = {}) => {
  options.method = 'get'
  return http(url, data, options)
}

const post = (url, data, options = {}) => {
  options.method = 'post'
  return http(url, data, options)
}

const put = (url, data, options = {}) => {
  options.method = 'put'
  return http(url, data, options)
}

const del = (url, data, options = {}) => {
  options.method = 'delete'
  return http(url, data, options)
}

const upload = (url, data, options = {}) => {
  options.method = 'post'
  return http(url, data, options)
}

export default {
  dom,
  get,
  post,
  put,
  del,
  upload
}
